//
//  HTTPMethod.m
//  NSURLSession版网络请求(AFN3.0)
//
//  Created by dllo on 15/10/27.
//  Copyright © 2015年 天才谢美娜. All rights reserved.
//

#import "HTTPMethod.h"
#import "ChangeString.h"

@implementation HTTPMethod

+(void)getDataByString:(NSString *)urlString BODYDic:(NSDictionary *)bodyDic WithDataBlock:(void (^)(id))dataBlock{
    //1.字符串转码
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];
    //2.创建管理者对象(session)
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //3.设置允许请求的类别
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", @"application/x-javascript", nil];
    //4.开始请求
    if (!bodyDic) {
        //GET;
        [manager GET:urlString parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            dataBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"😢");
        }];
    }else{
        //POST;
        [manager POST:urlString parameters:bodyDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            //判断是否为要缓存的对象
            if ([urlString isEqualToString:@"http://api2.pianke.me/pub/today"] && [bodyDic isEqualToDictionary:[ChangeString changeStringToDictionary:@"auth=&client=1&deviceid=DE384365-C3F9-468E-8E1A-3E78693E4D79&limit=10&start=0&version=3.0.6"]]) {
                NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documents = [array lastObject];
                NSString *documentPath = [documents stringByAppendingPathComponent:@"saveArray.plist"];
                [responseObject writeToFile:documentPath atomically:YES];
            }
            dataBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documents = [array lastObject];
            NSString *documentPath = [documents stringByAppendingPathComponent:@"saveArray.plist"];
            NSDictionary *resultDic = [NSDictionary dictionaryWithContentsOfFile:documentPath];
            dataBlock(resultDic);
            
        }];
    }
}

@end
